package org.op.editor.doc;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.swing.JEditorPane;
import javax.swing.text.Document;

import org.op.FrameView;
import org.op.editor.EditorComponentView;
import org.op.editor.TextFileFilter;
import org.op.menu.OpFileChooser;
import org.op.nav.NavigationController;
import org.op.service.WwDocumentInfo;
import org.op.service.config.ConfigKeys;
import org.op.service.config.ConfigurationService;
import org.op.service.doc.DocumentConversionService;
import org.op.service.fileio.FileRWService;
import org.op.service.log.LoggerService;
import org.op.util.MessageController;

public class DocumentPersistControllerImpl implements DocumentPersistController {

	private EditorComponentView editorView;
	private DocumentConversionService docConvertor;
	private FrameView frameView;
	private FileRWService fileRWService;
	private ConfigurationService configService;
	private MessageController messageController;
	private NavigationController navController;
	private LoggerService logger;
	
	/**
	 *  Open a FileChooser in the current directory of the given document
	 */
	public void saveAsDocument() {
		try {
			WwDocumentInfo docInfo = editorView.getCurrentDocumentInfo();
			Document document = editorView.getCurrentPane().getDocument();
			
			// get the current directory of the document (or workspace, if a new file)
			String currentPath = docInfo.getFilepath();  // can be null for a new file
			if (currentPath==null) {
				currentPath = configService.getProperty(ConfigKeys.KEY_CURRENT_WORKSPACE);
			}
			
			// open the filechooser in this directory
			OpFileChooser fileChooser = new OpFileChooser(frameView.getFrame(), currentPath);
			fileChooser.setApproveButtonText(messageController.getLabel("button.save"));
			fileChooser.setTitle(messageController.getLabel("save.dialog.title"));
			fileChooser.setFilter(new TextFileFilter());
			File newFile = fileChooser.openAndGet();
			
			// check to make sure the folder is in the workspace (what if not? -- who cares)
			
			// persist the file to this new location
			if (newFile!=null) {
				List<String> content = docConvertor.documentToText(document);
				fileRWService.writeFileText(newFile.getAbsolutePath(), content);
				
				// refresh the navigation tree
				navController.reloadTree();
				
				// update the document info object in the editor
				String newName = newFile.getName();
				int i = newName.indexOf(".");
				newName = newName.substring(0,i);
				
				// this may be updating the navigation tree - beware! 
				// (is OK, as long as the editor and tree docInfo's are not bound)
				docInfo.setName(newName);
				docInfo.setFilepath(newFile.getAbsolutePath());
				editorView.setCurrentDocumentInfo(docInfo);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			
			// TODO - show a user friendly message
			frameView.showExceptionDialog(e.getLocalizedMessage());
		}
	}

	public void saveDocument() {
		try {
			WwDocumentInfo docInfo = editorView.getCurrentDocumentInfo();
			Document document = editorView.getCurrentPane().getDocument();
			
			// get the current directory of the document (or workspace, if a new file)
			String currentPath = docInfo.getFilepath();
			if (currentPath == null) {
				// file does not exist, do a Save As instead
				saveAsDocument();
			} else {
				// persist the file to this new location
				List<String> content = docConvertor.documentToText(document);
				fileRWService.writeFileText(currentPath, content);
			}
			
			editorView.setClean(docInfo.getName());
			
		} catch (Exception e) {
			e.printStackTrace();
			// TODO - show a user friendly message
			frameView.showExceptionDialog(e.getLocalizedMessage());
		}

	}

	public void saveAllDocuments() {
		try {
			Map<WwDocumentInfo, JEditorPane> panes = editorView.getEditorPanes();
			Set<WwDocumentInfo> docInfos = panes.keySet();
			for (WwDocumentInfo docInfo : docInfos) {
				JEditorPane editor = panes.get(docInfo);
				Document doc = editor.getDocument();
				List<String> content = docConvertor.documentToText(doc);
				fileRWService.writeFileText(docInfo.getFilepath(), content);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			frameView.showExceptionDialog(e.getMessage());
		}
		
	}

	public EditorComponentView getEditorView() {
		return editorView;
	}

	public void setEditorView(EditorComponentView editorView) {
		this.editorView = editorView;
	}

	public DocumentConversionService getDocConvertor() {
		return docConvertor;
	}

	public void setDocConvertor(DocumentConversionService docConvertor) {
		this.docConvertor = docConvertor;
	}

	public FrameView getFrameView() {
		return frameView;
	}

	public void setFrameView(FrameView frameView) {
		this.frameView = frameView;
	}

	public FileRWService getFileRWService() {
		return fileRWService;
	}

	public void setFileRWService(FileRWService fileRWService) {
		this.fileRWService = fileRWService;
	}

	public ConfigurationService getConfigService() {
		return configService;
	}

	public void setConfigService(ConfigurationService configService) {
		this.configService = configService;
	}

	public MessageController getMessageController() {
		return messageController;
	}

	public void setMessageController(MessageController messageController) {
		this.messageController = messageController;
	}

	public NavigationController getNavController() {
		return navController;
	}

	public void setNavController(NavigationController navController) {
		this.navController = navController;
	}

	public LoggerService getLogger() {
		return logger;
	}

	public void setLogger(LoggerService logger) {
		this.logger = logger;
	}
	
}
